<?php

namespace App\Console\Commands;

use App\Models\ElectricCollector;
use App\Models\ElectricElectricity;
use App\Models\MqttModel;
use Illuminate\Console\Command;

class RealTimeData extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'real_time_data
                            {electric_code}
                            {device_type}
                            {collect_id}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '获取实时数据';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        [$args, $str] = $this->assemble();
        $topic = "realTime/{$args['collect_id']}";
        try {
            $result = (new MqttModel())->sendToDevice($str, $topic);
            $this->info(json_encode($result, JSON_UNESCAPED_UNICODE));
        } catch (\Exception $e) {
            $this->error(json_encode(['code' => '100', 'msg' => $e->getMessage()], JSON_UNESCAPED_UNICODE));
        }
    }

    /**
     * 拼装数据
     * @param Input $input
     * @param Output $output
     * @return array
     */
    public function assemble()
    {

        $args = $this->arguments();
        $ele_exit = ElectricElectricity::where(['tableAddress' => $args['electric_code']])->count();
        if ($ele_exit == 0) {
            $arr = ['code' => 100, 'msg' => '表地址所代表电表设备不存在'];
            $this->error(json_encode($arr, JSON_UNESCAPED_UNICODE));
        } else {
            $collector_exit = ElectricCollector::where(['code' => $args['collect_id']])->count();
            if ($collector_exit == 0) {
                $arr = ['code' => 100, 'msg' => '采集器不存在'];
                $this->error(json_encode($arr, JSON_UNESCAPED_UNICODE));
            } else {
                $str = [
                    "sync" => "true",//同步标识
                    "syncId" => "realTime/9999",//同步消息号
                    "ver" => 1,//消息版本号
                    "id" => $args['electric_code'],//表号
                    "devVer" => 2,//设备版本号
                    "type" => 2,//消息类型
                    "data" => [
                        "realTime" => 'true',
                        'device_type' => $args['device_type'],//设备类型·：1，电表；2，水表
                        'update_time' => date('Y-m-d H:i:s')
                    ]//数据区
                ];
                return array($args, $str);
            }
        }
    }
}
